Repository navigation
Do not narrow a comparison operand whose counterpart can be NAN - #7058
Conversation
Every ordering comparison with NAN is false, so the false branch of one tells nothing about the side opposite a NAN operand. The narrowing kept NAN on the side it narrowed, but still narrowed each side as if the other one were ordered, which turned a constant into never and cut ranges that the comparison leaves untouched.
The rewrite of count($a) < $x into $x <= count($a) with the negated context holds only under a total order: both comparisons are false for a NAN $x, so the false branch of the first one is not the true branch of the second, and it dropped NAN from $x.
Removing NAN from a type that cannot hold it leaves the type as it was. Asked as isSuperTypeOf() of the NAN constant, never came out as possibly NAN, because every type is a supertype of never. The count() rewrite skips a falsey context rather than only an exactly-false one, which keeps NAN out of the operand where the comparison is known not to be false.
SanderMuller
left a comment
There was a problem hiding this comment.
I compared the narrowing with real PHP 8.5. For 20 types I generated all 1,600 if ($a OP $b) pairs with <, <=, > and >=, and dumped both operands in both branches. The types include ints and int ranges, float, float ranges with and without NAN, NAN, 0.0|NAN, int|float, null, bool, int|null, float|null and strings. Then I checked each dumped type against the sample values that reach that branch in PHP.
- On 94519e2, 102 branches have a type that misses a value that reaches them. All of them are false branches. On this PR there are none.
- 176 dumped types change, all in a false branch, and every one gets wider.
Some of the wider types were already correct. When one operand is null or bool, PHP compares both sides as bools. NAN is then true, so it does not stop the order. For example, with ?int $a and float $f, the false branch of $a <= $f was int and is now int|null. null <= $f is true for every float, so int was right. This is only a loss of precision, and I am not sure it is worth a special case.
Two integration jobs are red because of this PR, and I think the new errors are correct. drupal and glpi each get one more occurrence of an error that their baseline already ignores:
- drupal
Role.php:223:$max > $role->weight ? $max : $role->weight + 1, where$maxismixed. - glpi
Contract.php:1301:$next_alert[$type]afterwhile ($next_alert[$type] < $previous_alert[$type]), where$previous_alert[$type]ismixed.
Before, the false branch narrowed the other operand against the mixed one and remembered that expression. That hid a second report of the same error. I reproduced both patterns. With an int or a string in place of the mixed operand, base and PR give the same errors.
The new nsrt file and testBug15713() fail without the change in BinaryOpHandler and pass with it. On 6896c23 I ran:
- the full test suite with and without the Turbo extension, 23,771 tests each, all pass,
make phpstanand phpcs, both pass,- the Turbo smoke test,
side-by-side.php,signature-parity.phpandwalk-trace.php, all pass, - the raw analysis output of the probe file and of
bug-15713.phpwith Turbo on and off, which is identical.
I could not run make lint-turbo because clang-tidy 21 is not installed here, but "Turbo Extension Lint" is green in CI. The other red jobs are also red on #7050 or on the 2.3.x tip.
Performance: I analysed a file with 400 functions and about 5,200 ordering comparisons, 8 runs per side. Wall-clock times were noisy on this machine, so I compare user CPU. Without Turbo it is 6.65 s on 2.3.x and 6.84 s with this PR. With Turbo it is 2.51 s and 2.44 s, which is within the noise.
There was a problem hiding this comment.
🟡 Changes recommended
The inverse comparison rewrite loses count narrowing when the right operand can be NAN, requiring matching PHP and C++ fixes and a regression assertion for the true branch.
1 open issue
What changed in this PR
This PR corrects PHPStan’s comparison narrowing when an operand can be NAN, preventing false positives in ordering comparisons and improving inferred min()/max() types.
Changes:
- Guard false-branch narrowing when the opposite operand can be NAN.
- Adjust count and string-length comparison rewrites, with matching native implementation changes.
- Add regression coverage for NAN comparisons and preserved narrowing.
| File | Description |
|---|---|
turbo-ext/src/generated/BinaryOpHandler.h |
Registers the native NAN-check helper. |
turbo-ext/src/BinaryOpHandler.cpp |
Mirrors the PHP narrowing and rewrite guards. |
tests/PHPStan/Rules/Comparison/NumberComparisonOperatorsConstantConditionRuleTest.php |
Checks expected comparison diagnostics for the regression fixture. |
tests/PHPStan/Analyser/nsrt/bug-15713.php |
Covers NAN inference, comparison branches, and min()/max(). |
src/Analyser/ExprHandler/BinaryOpHandler.php |
Adds NAN-aware guards to comparison narrowing and rewrites. |
Review effort: Balanced
| !$context->falsey() | ||
| || self::cannotBeNan($nativeTypesPromoted ? $rightResult->getNativeType() : $rightResult->getType()) |
Neither branch of count($a) < $x is a branch of $x <= count($a) when $x can be NAN, because both comparisons are false for a NAN. Restricting that to a falsey context left the true branch of the original computed as the false branch of the inverse, where the NAN guard then refused to narrow the count. The general path narrows each side on its own terms and keeps the bound.
|
Thanks for the grid. 102 unsound branches down to none is the check I could not run myself. I agree about The true branch did turn out to need work. The Copilot review found that the rewrite of a The drupal and glpi reports are correct. I said so in the PR body: the Mutation Testing went red with three escaped mutants on my guards and is green again. Thanks for measuring the cost. Your numbers show the type test without the extension, 6.65 s against 6.84 s. On my file of 2,400 comparisons I measured 1.44 s against 1.38 s, so the result depends on how many comparisons reach the guard. |
SanderMuller
left a comment
There was a problem hiding this comment.
I re-checked a916e03.
The count() rewrite now holds in both branches. I ran a second grid with count() and strlen() against the same 20 types, in both operand orders. That is 6,720 runtime checks: 324 unsound on the base and 0 on this head. Against 6896c23, all 56 changed types are true-branch narrowings, for example NAN|float<0.0, max> becomes float<0.0, max>. The new countBothBranches() assertions fail on the src of 6896c23, so the test covers the fix.
Agreed on null and bool.
The WordPress red is not from this PR. The red runs checked out WordPress at 24fa674, and the green runs on other PRs at 7924b71. The base reports the same three variable.undefined errors at 24fa674. The musl Turbo job could not pull alpine:3.24.
The full suite with and without the extension, phpstan, phpcs, lint-turbo, smoke, signature parity and walk-trace pass. The output is identical with the extension on and off on both grids. I timed a file of 2,400 count() and strlen() comparisons without the extension. User CPU was 4.93 s on the base and 4.76 s on this head.
|
Thank you! |

BinaryOpHandlernarrows both operands of<,<=,>and>=in the false branch. It keeps NAN on the side it narrows, but it still narrows each side as if the other one were ordered. This PR narrows a side only when the other side cannot be NAN.Impact
Every ordering comparison with NAN is false, so the false branch of one tells nothing about the side opposite a NAN operand.
-1|-2 $n, afterif (NAN >= $n) return;*NEVER*-2|-1int $i, afterif ($i < NAN) return;int<0, max>intint<-5, -1> $r→max(NAN, $r)NANNAN|int<-5, -1>int $i→max(NAN, $i)NAN|int<1, max>NAN|intbudget()reproducer of the issue,$ratio * $totalcan be0.0 * INF, which is NAN.$used < NANis false for every$used, so$used = -5reaches therefundbranch, but PHPStan narrowed$usedtoint<0, max>and reported the next comparison asComparison operation "<" between int<0, max> and 0 is always false.root(),sqrt(-0.5)is NAN, so$n = 3gets past the early return, but PHPStan narrowed$ntoint<min, 0>.sqrt()infer types likeNAN|float<0.0, max>, so code without a NAN literal reaches it.min()/max()of two arguments as the union of both comparison orders, and left the cases where an operand is not a literal to this.max(NAN, $r)now follows from the comparison, as it already did for literals.is_nan()keeps its precision. No existing test expectation changes.The same assumption of a total order sits in the rewrite of a
count()comparison, which this PR fixes in a second commit.$rootisNAN|float<0.0, 1.0>$rootafterif (count($a) < $root) return;float<0.0, 1.0>NAN|float<0.0, 1.0>$rootafterif (strlen($s) <= $root) return;float<0.0, 1.0>NAN|float<0.0, 1.0>$rootin the true branch ofcount($a) < $rootNAN|float<5.0E-324, 1.0>float<5.0E-324, 1.0>Cause
The false branch of
$a < $bhas two ways to be reached by a NAN:$ais NAN, and$bis NAN. The narrowing covered the first one by adding NAN to the type it assigns to$a, which is why$akeeps NAN. It did not cover the second one: when$bis NAN the comparison is false whatever$aholds, so the false branch puts no bound on$aat all, andgetGreaterOrEqualType()of a type that can be NAN is not a bound that holds. The same applies to$bwith the sides swapped.>and>=delegate to<and<=with the operands swapped, so they follow.count($a) < $xis specified as$x <= count($a)with the negated context, which the comment calls what aBooleanNotaround the inverse operator would do. That holds only under a total order. For a NAN$xboth comparisons are false, so the false branch of the first one is not the true branch of the second, and the narrowing of the true branch of$x <= count($a)dropped NAN from$x.Fix
Each of the two narrowings in the false branch now runs only when the other operand cannot be NAN, and the
count()rewrite is skipped whenever the other operand can be NAN, in every context, so that comparison takes the general path instead. The general path narrows each side on its own terms and keeps the bounds the rewrite used to give: in the true branch ofcount($a) < $rootthe count is still0for a$rootbelow1.0, and$rootcomes out without NAN, which a true ordering comparison does rule out. The narrowing of the true branch of an ordering comparison is otherwise unchanged, because it already rules out NAN on both sides. The nativeBinaryOpHandlerin turbo-ext gets the same changes.cannotBeNan()asks the question by removing NAN from the type and comparing: removing NAN from a type that cannot hold it leaves the type as it was. Asked asisSuperTypeOf()of the NAN constant, asFloatRangeType::accepts()does,nevercomes out as possibly NAN, because every type is a supertype ofnever.Testing
tests/PHPStan/Analyser/nsrt/bug-15713.phpcovers the two reproducers from the issue, a literal NAN on either side, themin()/max()cases and the comparisons that keep narrowing.NumberComparisonOperatorsConstantConditionRuleTest::testBug15713()holds the errors the same file produces: the false positive is gone, and the comparison that really is always false is still reported.The integration runs of drupal and glpi report one error more than their baseline allows, at
Role.php:223andContract.php:1301. Both compare against amixedoperand, and the narrowing this PR removes used to remember that expression, which hid a second report of the same error. The new reports are correct. Thecount:of each entry lives in the analysed project's own baseline at the pinned ref, so this PR cannot adjust it.Closes phpstan/phpstan#15713